package com.dy.project.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dy.project.domain.AjaxResult;
import com.dy.project.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice
public class AjaxExceptionHandler {
    @Autowired
    private LogUtil logUtil;
    @ExceptionHandler(value = Exception.class)
    public AjaxResult defaultErrorHandler(HttpServletRequest request, Exception ex) throws Exception{
        ex.printStackTrace();
        logUtil.error(ex.getMessage());
        if(ex instanceof BindException){
            List<ObjectError> errors = ((BindException) ex).getAllErrors();
            JSONArray errArray = new JSONArray();
            for(ObjectError err:errors){
                FieldError fieldError = (FieldError)err;
                JSONObject errObj = new JSONObject();
                errObj.put("field",fieldError.getField());
                errObj.put("errMsg",fieldError.getDefaultMessage());
                errArray.add(errObj);
            }
            return new AjaxResult().err(500,errArray.toJSONString());
        }
        return new AjaxResult().err(500,ex.getMessage());
    }
}
